package sk.stuba.fiit.foo07.genex.gui;

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.SplashScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import sk.stuba.fiit.foo07.genex.beans.Category;
import sk.stuba.fiit.foo07.genex.beans.Question;
import sk.stuba.fiit.foo07.genex.beans.Test;
import sk.stuba.fiit.foo07.genex.common.ConnectionHelper;
import sk.stuba.fiit.foo07.genex.common.DerbyDBTools;
import sk.stuba.fiit.foo07.genex.common.ResourceHelper;
import sk.stuba.fiit.foo07.genex.dao.CategoryDao;
import sk.stuba.fiit.foo07.genex.dao.CategoryDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionDao;
import sk.stuba.fiit.foo07.genex.dao.QuestionDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.QuestionTypeDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.TestDao;
import sk.stuba.fiit.foo07.genex.dao.TestDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.UserDao;
import sk.stuba.fiit.foo07.genex.dao.UserDaoDerby;
import sk.stuba.fiit.foo07.genex.exceptions.TestInTestCategoryException;
import sk.stuba.fiit.foo07.genex.export.Export;
import sk.stuba.fiit.foo07.genex.export.ExportMoodle;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class GenexGUI extends javax.swing.JFrame implements
        ListSelectionListener, ActionListener, MouseListener,
        TreeSelectionListener, ChangeListener {

    /**
     * 
     */

    public static final Color COMB1_FOREGROUND_COLOR = new java.awt.Color(0, 0,
            255);
    public static final Color COMB1_BACKGROUND_COLOR = new java.awt.Color(255,
            255, 190);
    public static final Color COMB2_FOREGROUND_COLOR = new java.awt.Color(255,
            255, 255);
    public static final Color COMB2_BACKGROUND_COLOR = new java.awt.Color(0, 0,
            0);

    private static final long serialVersionUID = 5089384553716451243L;

    private Connection connection;
    private ResourceHelper resHelp;
    private ImageIcon categoryIcon;
    private ImageIcon questionIcon;
    private GenexTableModel genexTableModel;
    private DefaultMutableTreeNode rootQuestionCategoryNode;
    private DefaultMutableTreeNode rootTestCategoryNode;
    private CategoryDao categoryDao;
    private QuestionDao questionDao;
    private UserDao userDao;
    private TestDao testDao;
    private static String version;
    private NewTestDialog ntd;
    private boolean lastSelTable = false;

    private JScrollPane jScrollTab2;
    private JScrollPane jScrollTab1;
    private JTabbedPane jTabPane;
    private JToolBar jToolBar;
    private JSplitPane jSplitToolbar;
    private JButton jBtnFind;
    private JScrollPane jSrcollHint;
    private JButton jBtnNewTest;
    private JButton jBtnNewQCategory;
    private JTextArea jTxtQuestionText;
    private JScrollPane jScrollQuestionText;
    private JScrollPane jScrollTable;
    private JTree jTreeTCategories;
    private JTree jTreeQCategories;
    private JMenuBar jMbrMainMenu;
    private JMenu jMnuFile;
    private JMenu jMnuTest;
    private JMenuItem jMtmPaste;
    private JMenuItem jMtmFind;
    private JSeparator jSprFind;
    private JTextPane jTxtHint;
    private JButton jBtnGenTest;
    private JButton jBtnDelete;
    private JMenuItem jMtmExport;
    private JMenuItem jMtmExportMoodle;
    private JSeparator jSprImportexport;
    private JButton jBtnCopy;
    private JButton jBtnCut;
    private JButton jBtnPaste;
    private JPopupMenu jTablePopup;
    private JPopupMenu jTestCategoriesPopup;
    private JPopupMenu jQuestionCategoriesPopupMenu;
    private JButton jBtnNewQuestion;
    private JTable jTblQuestions;
    private JSplitPane jSplitCenter;
    private JSplitPane jSplitLeftRight;
    private JSeparator jSprSettings;
    private JMenuItem jMtmNewQuestion;
    private JMenuItem jMtmNewCategory;
    private JMenuItem jMtmAbout;
    private JSeparator jSprAbout;
    private JMenuItem jMtmHelp;
    private JMenuItem jMtmGenerateTest;
    private JMenuItem jMtmNewTest;
    private JMenuItem jMtmDelete;
    private JSeparator jSprDelete;
    private JSeparator jSprAddQuestions;
    private JMenuItem jMtmCopy;
    private JMenuItem jMtmAddQuestions;
    private JMenuItem jMtmCut;
    private JMenuItem jMtmEdit;
    private JMenuItem jMtmJumpDerived;
    private JMenuItem jMtmQuit;
    private JMenuItem jMtmSettings;
    private JSeparator jSprQuit;
    private JMenu jMnuHelp;
    private JMenu jMnuEdit;
    private JButton jBtnEdit;
    private JButton jBtnUp;
    private JButton jBtnAdd;

    /**
     * Auto-generated main method to display this JFrame
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                try {
                    InputStream dataStream = getClass().getResourceAsStream(
                            "/app.properties");
                    Properties prop = new Properties();
                    prop.load(dataStream);
                    version = prop.getProperty("application.version");

                    SplashScreen splash = SplashScreen.getSplashScreen();
                    if (splash != null) {
                        splashScreenWrite("Starting Genex", splash);
                    }
                    // load derby embedded driver
                    if (splash != null) {
                        splashScreenWrite("Loading database driver", splash);
                    }
                    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

                    if (splash != null) {
                        splashScreenWrite("Connecting to database", splash);
                    }
                    // create and connect to new derby database
                    Connection con = DriverManager.getConnection("jdbc:derby:"
                            + "genexdb" + ";create=true");

                    if (!DerbyDBTools.databaseInitialized(con)) {
                        if (splash != null) {
                            splashScreenWrite("Initializing database", splash);
                        }
                        DerbyDBTools.runScript(con, "/ddl/ddl.sql");
                        DerbyDBTools.runScript(con, "/ddl/commonData.sql");
                        DerbyDBTools.loadData(con, "/data.xml");
                    }
                    if (splash != null) {
                        splashScreenWrite("Ready", splash);
                    }

                    GenexGUI inst = new GenexGUI(con);
                    inst.setLocationRelativeTo(null);
                    inst.setVisible(true);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    System.err
                            .println("Apache derby library not found in classpath");
                } catch (SQLException e) {
                    System.err.println("Connection to database failed " + e);
                } catch (UnsupportedEncodingException e) {
                    System.err.println("Initialization scripts failed");
                } catch (IOException ex) {
                    System.err
                            .println("Loading basic app configuration failed");
                }

            }
        });
    }

    private static void splashScreenWrite(String text, SplashScreen splash) {
        Graphics2D g = splash.createGraphics();

        Rectangle size = splash.getBounds();

        g.drawString(version, 150, 85);
        g.setComposite(AlphaComposite.Clear);
        g.setPaintMode();
        g.setBackground(Color.WHITE);

        g.fillRect(size.width - 300, size.height - 100, 200, 20);
        g.setColor(Color.BLACK);
        g.drawString(text, size.width - 280, size.height - 85);
        String license = "Released under GNU GPLv2";
        g.drawString(license, size.width - 280, size.height - 60);
        splash.update();
    }

    public GenexGUI(Connection con) {
        super();

        this.connection = con;
        ConnectionHelper.setConnection(con);

        resHelp = new ResourceHelper();
        categoryIcon = new ImageIcon(resHelp
                .getResourceBytes("/icons/closedcat.png"));
        questionIcon = new ImageIcon(resHelp
                .getResourceBytes("/icons/questionicon.png"));

        categoryDao = new CategoryDaoDerby(connection);
        questionDao = new QuestionDaoDerby(connection);
        userDao = new UserDaoDerby(connection);
        testDao = new TestDaoDerby(connection);

        // kategorie otazok
        //TODO
        //pridane odchytavanie vynimiek (palo)
        try {
            Category root = categoryDao.getRootCategories().get(0);
            rootQuestionCategoryNode = new DefaultMutableTreeNode(root);
            ArrayList<Category> cats = null; //pozor mozna chyba

            cats = categoryDao.getCategoriesByParentID(root.getCategoryID());

            for (Category c : cats) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(c);
                rootQuestionCategoryNode.add(node);
                if (categoryDao.hasSubcategories(c.getCategoryID()))
                    node.add(new DefaultMutableTreeNode("camuflage"));
            }

            root = categoryDao.getRootTestCategories().get(0);
            rootTestCategoryNode = new DefaultMutableTreeNode(root);
            cats = categoryDao
                    .getTestCategoriesByParentID(root.getCategoryID());
            for (Category c : cats) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(c);
                rootTestCategoryNode.add(node);
                if (categoryDao.hasTestSubcategories(c.getCategoryID())
                        || testDao.getTestsByCategoryID(c.getCategoryID())
                                .size() > 0)
                    node.add(new DefaultMutableTreeNode("camuflage"));
            }
            ArrayList<Test> tests = testDao.getTestsByCategoryID(root
                    .getCategoryID());
            for (Test test : tests)
                rootTestCategoryNode.add(new DefaultMutableTreeNode(test));

            genexTableModel = new GenexTableModel(categoryIcon, questionIcon,
                    categoryDao, questionDao, new QuestionTypeDaoDerby(
                            connection));
        } catch (Exception e) {
        }
        initGUI();
        ntd = new NewTestDialog();
        jTreeQCategories.setSelectionRow(0);
        jTreeTCategories.setSelectionRow(0);
        setTreesIcons();
        ToolTipManager.sharedInstance().unregisterComponent(jTblQuestions);
        ToolTipManager.sharedInstance().unregisterComponent(
                jTblQuestions.getTableHeader());

        initPopups();
    }

    private void initPopups() {
        // TODO doplnit init popup okien
        JMenuItem item;

        item = new JMenuItem(jMtmNewCategory.getText());
        item.addActionListener(this);
        jTablePopup.add(item);
        item = new JMenuItem(jMtmNewQuestion.getText());
        item.addActionListener(this);
        jTablePopup.add(item);

        jTablePopup.add(new JSeparator());

        item = new JMenuItem(jMtmEdit.getText());
        item.addActionListener(this);
        jTablePopup.add(item);
        item = new JMenuItem(jMtmCut.getText());
        item.addActionListener(this);
        jTablePopup.add(item);
        item = new JMenuItem(jMtmCopy.getText());
        item.addActionListener(this);
        jTablePopup.add(item);
        item = new JMenuItem(jMtmPaste.getText());
        item.addActionListener(this);
        jTablePopup.add(item);

        item = new JMenuItem(jMtmJumpDerived.getText());
        item.addActionListener(this);
        jTablePopup.add(item);

        item = new JMenuItem(jMtmDelete.getText());
        item.addActionListener(this);
        jTablePopup.add(item);

        jTablePopup.add(new JSeparator());

        item = new JMenuItem("Pridať do testu");
        item.addActionListener(this);
        jTablePopup.add(item);
    }

    private void setTreesIcons() {
        DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer();
        ImageIcon icon1 = new ImageIcon(resHelp
                .getResourceBytes("/icons/closedcat.png"));
        ImageIcon icon2 = new ImageIcon(resHelp
                .getResourceBytes("/icons/opencat.png"));
        ImageIcon icon3 = new ImageIcon(resHelp
                .getResourceBytes("/icons/leafcat.png"));
        if (icon1 != null && icon2 != null && icon3 != null) {
            cellRenderer.setClosedIcon(icon1);
            cellRenderer.setOpenIcon(icon2);
            cellRenderer.setLeafIcon(icon3);
        }

        jTreeQCategories.setCellRenderer(cellRenderer);

        DefaultTreeCellRenderer cellRenderer2 = new TreeIconRenderer();
        icon1 = new ImageIcon(resHelp.getResourceBytes("/icons/closedcat.png"));
        icon2 = new ImageIcon(resHelp.getResourceBytes("/icons/opencat.png"));
        icon3 = new ImageIcon(resHelp.getResourceBytes("/icons/leaftest.png"));
        if (icon1 != null && icon2 != null && icon3 != null) {
            cellRenderer2.setClosedIcon(icon1);
            cellRenderer2.setOpenIcon(icon2);
            cellRenderer2.setLeafIcon(icon3);
        }

        jTreeTCategories.setCellRenderer(cellRenderer2);
    }

    private void initGUI() {

        try {
            {
                this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                this.setTitle("GenEx - Tvorba testov");
                this.addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent evt) {
                        jSplitCenter.setDividerLocation(0.75);
                    }
                });
                this.addFocusListener(new FocusAdapter() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        genexTableModel.fireTableDataChanged();
                    }
                });
            }
            {
                QuestionCategoryTreeListener listener1 = new QuestionCategoryTreeListener(
                        connection, genexTableModel);
                jSplitToolbar = new JSplitPane();
                getContentPane().add(jSplitToolbar, BorderLayout.CENTER);
                jSplitToolbar.setOrientation(JSplitPane.VERTICAL_SPLIT);
                {
                    jSplitLeftRight = new JSplitPane();
                    jSplitToolbar.add(jSplitLeftRight, JSplitPane.RIGHT);
                    jSplitLeftRight.setPreferredSize(new java.awt.Dimension(
                            875, 472));
                    {
                        jTabPane = new JTabbedPane();
                        jTabPane.addChangeListener(this);
                        jSplitLeftRight.add(jTabPane, JSplitPane.LEFT);
                        jTabPane.setPreferredSize(new java.awt.Dimension(159,
                                488));
                        {
                            jScrollTab1 = new JScrollPane();
                            jTabPane.addTab("Otázky", null, jScrollTab1, null);
                            {
                                jTreeQCategories = new JTree(
                                        rootQuestionCategoryNode);
                                jScrollTab1.setViewportView(jTreeQCategories);
                                jTreeQCategories.setShowsRootHandles(true);
                                jTreeQCategories.setRootVisible(true);
                                jTreeQCategories
                                        .setToolTipText("Kategórie otázok");
                                jTreeQCategories
                                        .getSelectionModel()
                                        .setSelectionMode(
                                                TreeSelectionModel.SINGLE_TREE_SELECTION);
                                jTreeQCategories
                                        .setBackground(new java.awt.Color(255,
                                                255, 240));
                                jTreeQCategories.setDragEnabled(true);
                                {
                                    jQuestionCategoriesPopupMenu = new JPopupMenu();
                                    setComponentPopupMenu(jTreeQCategories,
                                            jQuestionCategoriesPopupMenu);
                                }
                                jTreeQCategories
                                        .addTreeSelectionListener(listener1);
                                jTreeQCategories
                                        .addTreeWillExpandListener(listener1);
                            }
                        }
                        {
                            jScrollTab2 = new JScrollPane();
                            jTabPane.addTab("Testy", null, jScrollTab2, null);
                            {
                                jTreeTCategories = new JTree(
                                        rootTestCategoryNode);
                                jScrollTab2.setViewportView(jTreeTCategories);
                                jTreeTCategories.setShowsRootHandles(true);
                                jTreeTCategories.setRootVisible(true);
                                jTreeTCategories
                                        .setToolTipText("Kategórie testov");
                                jTreeTCategories
                                        .setPreferredSize(new java.awt.Dimension(
                                                151, 392));
                                jTreeTCategories
                                        .getSelectionModel()
                                        .setSelectionMode(
                                                TreeSelectionModel.SINGLE_TREE_SELECTION);
                                jTreeTCategories
                                        .setBackground(new java.awt.Color(255,
                                                255, 240));
                                jTreeTCategories
                                        .addMouseListener(new MouseAdapter() {
                                            @Override
                                            public void mouseClicked(
                                                    MouseEvent evt) {
                                                jTreeTCategoriesMouseClicked(evt);
                                            }
                                        });
                                jTreeTCategories
                                        .addFocusListener(new FocusAdapter() {
                                            @Override
                                            public void focusGained(FocusEvent e) {
                                                lastSelTable = false;
                                            }
                                        });
                                {
                                    jTestCategoriesPopup = new JPopupMenu();
                                    setComponentPopupMenu(jTreeTCategories,
                                            jTestCategoriesPopup);
                                }
                                TestCategoryTreeListener listener = new TestCategoryTreeListener(
                                        connection);
                                jTreeTCategories
                                        .addTreeWillExpandListener(listener);
                                jTreeTCategories.addTreeSelectionListener(this);
                            }
                        }
                    }
                    {
                        jSplitCenter = new JSplitPane();
                        jSplitLeftRight.add(jSplitCenter, JSplitPane.RIGHT);
                        jSplitCenter.setOrientation(JSplitPane.VERTICAL_SPLIT);
                        {
                            jScrollTable = new JScrollPane();
                            jSplitCenter.add(jScrollTable, JSplitPane.LEFT);
                            jScrollTable
                                    .setPreferredSize(new java.awt.Dimension(
                                            694, 340));
                            jScrollTable.getViewport().setBackground(
                                    new Color(255, 255, 240));
                            {
                                jTablePopup = new JPopupMenu();
                                setComponentPopupMenu(jScrollTable, jTablePopup);
                            }
                            {
                                jTblQuestions = new JTable();
                                jScrollTable.setViewportView(jTblQuestions);
                                jTblQuestions.setModel(genexTableModel);
                                jTblQuestions.setShowGrid(false);
                                jTblQuestions.setBackground(new java.awt.Color(
                                        255, 255, 240));
                                jTblQuestions
                                        .setToolTipText("Otázky a kategórie");
                                //jTblQuestions.setAutoCreateRowSorter(true);
                                jTblQuestions.setDragEnabled(true);

                                jTblQuestions
                                        .getColumnModel()
                                        .getColumn(0)
                                        .setCellRenderer(new IconCellRenderer());
                                jTblQuestions.getColumnModel().getColumn(0)
                                        .setMinWidth(20);
                                jTblQuestions.getColumnModel().getColumn(0)
                                        .setMaxWidth(20);
                                jTblQuestions.getColumnModel().getColumn(0)
                                        .setPreferredWidth(20);
                                jTblQuestions.getColumnModel().getColumn(0)
                                        .setResizable(false);
                                jTblQuestions.getColumnModel().getColumn(1)
                                        .setPreferredWidth(320);

                                jTblQuestions.getColumnModel().getColumn(2)
                                        .setPreferredWidth(10);
                                jTblQuestions.getColumnModel().getColumn(2)
                                        .setCellRenderer(
                                                new ColoredTextRenderer());
                                jTblQuestions.getColumnModel().getColumn(3)
                                        .setPreferredWidth(100);
                                jTblQuestions.getColumnModel().getColumn(3)
                                        .setCellRenderer(
                                                new ProgressCellRenderer());
                                jTblQuestions.getColumnModel().getColumn(4)
                                        .setPreferredWidth(100);
                                jTblQuestions.getColumnModel().getColumn(4)
                                        .setCellRenderer(
                                                new ColoredTextRenderer());
                                jTblQuestions.getColumnModel().getColumn(5)
                                        .setPreferredWidth(20);
                                jTblQuestions.getColumnModel().getColumn(5)
                                        .setMinWidth(20);
                                jTblQuestions.getSelectionModel()
                                        .addListSelectionListener(this);
                                listener1.setGenexTable(jTblQuestions);
                                jTblQuestions.addMouseListener(this);
                                {
                                    setComponentPopupMenu(jTblQuestions,
                                            jTablePopup);
                                }
                                jTblQuestions
                                        .addFocusListener(new FocusAdapter() {
                                            @Override
                                            public void focusGained(FocusEvent e) {
                                                lastSelTable = true;
                                            }
                                        });
                            }
                        }
                        {
                            jScrollQuestionText = new JScrollPane();
                            jSplitCenter.add(jScrollQuestionText,
                                    JSplitPane.RIGHT);
                            jScrollQuestionText
                                    .setPreferredSize(new java.awt.Dimension(
                                            647, 103));
                            {
                                jTxtQuestionText = new JTextArea();
                                jScrollQuestionText
                                        .setViewportView(jTxtQuestionText);
                                jTxtQuestionText.setText("Text otázky.");
                                jTxtQuestionText
                                        .setBackground(new java.awt.Color(255,
                                                255, 240));
                                jTxtQuestionText
                                        .setForeground(new java.awt.Color(100,
                                                0, 0));
                                jTxtQuestionText
                                        .setToolTipText("Text vybranej otázky");
                                jTxtQuestionText.setEditable(false);
                                jTxtQuestionText.setDragEnabled(true);
                            }
                        }
                    }
                }
                {
                    jToolBar = new JToolBar();
                    jSplitToolbar.add(jToolBar, JSplitPane.LEFT);
                    jToolBar.setPreferredSize(new java.awt.Dimension(875, 34));
                    jToolBar.setFloatable(false);
                    {
                        jBtnNewQCategory = new JButton();
                        jToolBar.add(jBtnNewQCategory);
                        jBtnNewQCategory.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/newcat.png")));
                        jBtnNewQCategory
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnNewQCategory
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnNewQCategory.setToolTipText("Nová kategória");
                        jBtnNewQCategory.setActionCommand("Nová kategória");
                        jBtnNewQCategory.addActionListener(this);
                    }
                    {
                        jBtnNewQuestion = new JButton();
                        jToolBar.add(jBtnNewQuestion);
                        jBtnNewQuestion.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/newquestion.png")));
                        jBtnNewQuestion
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnNewQuestion
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnNewQuestion.setToolTipText("Nová otázka");
                        jBtnNewQuestion.setActionCommand("Nová otázka");
                        jBtnNewQuestion.addActionListener(this);
                    }
                    {
                        jBtnEdit = new JButton();
                        jToolBar.add(jBtnEdit);
                        jBtnEdit.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/edit.png")));
                        jBtnEdit.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnEdit
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnEdit.setToolTipText("Upraviť");
                        jBtnEdit.setActionCommand("Upraviť");
                        jBtnEdit.addActionListener(this);
                    }
                    {
                        jBtnCut = new JButton();
                        jToolBar.add(jBtnCut);
                        jBtnCut.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/cut.png")));
                        jBtnCut.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnCut
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnCut.setToolTipText("Vystrihnúť");
                        jBtnCut.setActionCommand("Vystrihnúť");
                        jBtnCut.addActionListener(this);
                    }
                    {
                        jBtnCopy = new JButton();
                        jToolBar.add(jBtnCopy);
                        jBtnCopy.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/copy.png")));
                        jBtnCopy.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnCopy
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnCopy.setToolTipText("Kopírovať");
                        jBtnCopy.setActionCommand("Kopírovať");
                        jBtnCopy.addActionListener(this);
                    }
                    {
                        jBtnPaste = new JButton();
                        jToolBar.add(jBtnPaste);
                        jBtnPaste.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/paste.png")));
                        jBtnPaste
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnPaste
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnPaste.setToolTipText("Vložiť");
                        jBtnPaste.setActionCommand("Vložiť");
                        jBtnPaste.addActionListener(this);
                    }
                    {
                        jBtnDelete = new JButton();
                        jToolBar.add(jBtnDelete);
                        jBtnDelete.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/delete.png")));
                        jBtnDelete
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnDelete
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnDelete.setToolTipText("Odstrániť");
                        jBtnDelete.setActionCommand("Odstrániť");
                        jBtnDelete.addActionListener(this);
                    }
                    {
                        jBtnNewTest = new JButton();
                        jToolBar.add(jBtnNewTest);
                        jBtnNewTest.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/newtest.png")));
                        jBtnNewTest
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnNewTest
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnNewTest.setToolTipText("Nový test");
                        jBtnNewTest.setActionCommand("Nový");
                        jBtnNewTest.addActionListener(this);
                    }
                    {
                        jBtnGenTest = new JButton();
                        jToolBar.add(jBtnGenTest);
                        jBtnGenTest.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/gentest.png")));
                        jBtnGenTest
                                .setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnGenTest
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnGenTest.setToolTipText("Generova\u0165 test");
                        jBtnGenTest.setActionCommand("Generova\u0165");
                        jBtnGenTest.addActionListener(this);
                    }
                    {
                        jBtnUp = new JButton();
                        jToolBar.add(jBtnUp);
                        jBtnUp.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/bigup.png")));
                        jBtnUp.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnUp.setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnUp.setToolTipText("O úroven vyššie");
                        jBtnUp.setActionCommand("O úroven vyššie");
                        jBtnUp.addActionListener(this);
                    }
                    {
                        jBtnAdd = new JButton();
                        jToolBar.add(jBtnAdd);
                        jBtnAdd.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/addbig.png")));
                        jBtnAdd.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnAdd
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnAdd
                                .setToolTipText("Pridať vybranú(é) otázku(y) to testu");
                        jBtnAdd.setActionCommand("Pridať do testu");
                        jBtnAdd.addActionListener(this);
                    }
                    {
                        jSrcollHint = new JScrollPane();
                        jToolBar.add(jSrcollHint);
                        {
                            jTxtHint = new JTextPane();
                            jSrcollHint.setViewportView(jTxtHint);
                            hint("Info: Ukončiť aplikáciu môžete kliknutim na krížik v pravom hornom rohu.");
                            jTxtHint.setBackground(COMB1_BACKGROUND_COLOR);
                            jTxtHint.setForeground(COMB1_FOREGROUND_COLOR);
                            jTxtHint.setToolTipText("Rýchla pomoc");
                            jTxtHint.setEditable(false);
                        }
                    }
                    {
                        jBtnFind = new JButton();
                        jToolBar.add(jBtnFind);
                        jBtnFind.setIcon(new ImageIcon(resHelp
                                .getResourceBytes("/icons/find.png")));
                        jBtnFind.setVerticalTextPosition(SwingConstants.BOTTOM);
                        jBtnFind
                                .setHorizontalTextPosition(SwingConstants.CENTER);
                        jBtnFind.setToolTipText("H\u013eada\u0165");
                        jBtnFind.setActionCommand("H\u013eada\u0165");
                        jBtnFind.addActionListener(this);
                    }
                }
            }
            this.setSize(885, 611);
            // START >> jMbrMainMenu
            jMbrMainMenu = new JMenuBar();
            setJMenuBar(jMbrMainMenu);
            jMbrMainMenu.setToolTipText("Hlavná ponuka");
            // START >> jMnuSubor
            jMnuFile = new JMenu();
            jMbrMainMenu.add(jMnuFile);
            jMnuFile.setText("Súbor");
            jMnuFile.setMnemonic(java.awt.event.KeyEvent.VK_S);
            // START >> jMtmNovaKategoria
            jMtmNewCategory = new JMenuItem();
            jMnuFile.add(jMtmNewCategory);
            jMtmNewCategory.setText("Nová kategória");
            jMtmNewCategory.setActionCommand("Nová kategória");
            jMtmNewCategory.addActionListener(this);
            jMtmNewCategory.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menunewcat.png")));
            jMtmNewCategory.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_K, ActionEvent.CTRL_MASK));
            jMtmNewCategory.setMnemonic(java.awt.event.KeyEvent.VK_K);
            // END << jMtmNovaKategoria
            // START >> jMtmNovaOtazka
            jMtmNewQuestion = new JMenuItem();
            jMnuFile.add(jMtmNewQuestion);
            jMtmNewQuestion.setText("Nová otázka");
            jMtmNewQuestion.setActionCommand("Nová otázka");
            jMtmNewQuestion.addActionListener(this);
            jMtmNewQuestion.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menunewquestion.png")));
            jMtmNewQuestion.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_O, ActionEvent.CTRL_MASK));
            jMtmNewQuestion.setMnemonic(java.awt.event.KeyEvent.VK_O);
            // END << jMtmNovaOtazka
            {
                jSprImportexport = new JSeparator();
                jMnuFile.add(jSprImportexport);
            }
            {
                jMtmExport = new JMenuItem();
                jMnuFile.add(jMtmExport);
                jMtmExport.setText("Export testu do LaTeXu");
                jMtmExport.setActionCommand("Export testu");
                jMtmExport.addActionListener(this);
                jMtmExport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
                        ActionEvent.CTRL_MASK));
                jMtmExport.setMnemonic(java.awt.event.KeyEvent.VK_E);
            }
            {
                jMtmExportMoodle = new JMenuItem();
                jMnuFile.add(jMtmExportMoodle);
                jMtmExportMoodle.setText("Export testu do Moodle");
                jMtmExportMoodle.setActionCommand("Export testu do Moodle");
                jMtmExportMoodle.addActionListener(this);
                jMtmExportMoodle.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_M, ActionEvent.CTRL_MASK));
                jMtmExportMoodle.setMnemonic(java.awt.event.KeyEvent.VK_M);
            }
            // START >> jSprNastavenia
            jSprSettings = new JSeparator();
            jMnuFile.add(jSprSettings);
            // END << jSprNastavenia
            // START >> jMtmNastavenia
            jMtmSettings = new JMenuItem();
            jMnuFile.add(jMtmSettings);
            jMtmSettings.setText("Nastavenia");
            jMtmSettings.setActionCommand("Nastavenia");
            jMtmSettings.addActionListener(this);
            jMtmSettings.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menusettings.png")));
            jMtmSettings.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
                    ActionEvent.CTRL_MASK));
            jMtmSettings.setMnemonic(java.awt.event.KeyEvent.VK_N);
            // END << jMtmNastavenia
            // START >> jSprUkoncit
            jSprQuit = new JSeparator();
            jMnuFile.add(jSprQuit);
            // END << jSprUkoncit
            // START >> jMtmUkoncit
            jMtmQuit = new JMenuItem();
            jMnuFile.add(jMtmQuit);
            jMtmQuit.setText("Ukon\u010di\u0165");
            jMtmQuit.setActionCommand("Ukon\u010di\u0165");
            jMtmQuit.addActionListener(this);
            jMtmQuit.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menuexit.png")));
            jMtmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
                    ActionEvent.CTRL_MASK));
            jMtmQuit.setMnemonic(java.awt.event.KeyEvent.VK_U);
            // END << jMtmUkoncit
            // END << jMnuSubor
            // START >> jMnuUpravy
            jMnuEdit = new JMenu();
            jMbrMainMenu.add(jMnuEdit);
            jMnuEdit.setText("Úpravy");
            jMnuEdit.setMnemonic(java.awt.event.KeyEvent.VK_P);
            // START >> jMtmFind
            jMtmEdit = new JMenuItem();
            jMnuEdit.add(jMtmEdit);
            jMtmEdit.setText("Upraviť");
            jMtmEdit.setActionCommand("Upraviť");
            jMtmEdit.addActionListener(this);
            jMtmEdit.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menuedit.png")));
            jMtmEdit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
                    ActionEvent.CTRL_MASK));
            jMtmEdit.setMnemonic(java.awt.event.KeyEvent.VK_U);
            // END << jMtmFind
            // START >> jSprFind
            jSprFind = new JSeparator();
            jMnuEdit.add(jSprFind);
            // END << jSprFind
            // START >> jMtmVystrihnut
            jMtmCut = new JMenuItem();
            jMnuEdit.add(jMtmCut);
            jMtmCut.setText("Vystrihnúť");
            jMtmCut.setActionCommand("Vystrihnúť");
            jMtmCut.addActionListener(this);
            jMtmCut.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menucut.png")));
            jMtmCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
                    ActionEvent.CTRL_MASK));
            jMtmCut.setMnemonic(java.awt.event.KeyEvent.VK_S);
            // END << jMtmVystrihnut
            // START >> jMtmKopirovat
            jMtmCopy = new JMenuItem();
            jMnuEdit.add(jMtmCopy);
            jMtmCopy.setText("Kopírovať");
            jMtmCopy.setActionCommand("Kopírovať");
            jMtmCopy.addActionListener(this);
            jMtmCopy.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menucopy.png")));
            jMtmCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
                    ActionEvent.CTRL_MASK));
            jMtmCopy.setMnemonic(java.awt.event.KeyEvent.VK_K);
            // END << jMtmKopirovat
            // START >> jMtmVlozit
            jMtmPaste = new JMenuItem();
            jMnuEdit.add(jMtmPaste);
            jMtmPaste.setText("Vložiť");
            jMtmPaste.setActionCommand("Vložiť");
            jMtmPaste.addActionListener(this);
            jMtmPaste.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menupaste.png")));
            jMtmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
                    ActionEvent.CTRL_MASK));
            jMtmPaste.setMnemonic(java.awt.event.KeyEvent.VK_V);
            // END << jMtmVlozit
            // START >> jMtm
            jMtmJumpDerived = new JMenuItem();
            jMnuEdit.add(jMtmJumpDerived);
            jMtmJumpDerived.setText("Ísť na pôvodnú otázku");
            jMtmJumpDerived.setActionCommand("Ísť na pôvodnú otázku");
            jMtmJumpDerived.addActionListener(this);
            jMtmJumpDerived.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menupaste.png")));
            jMtmPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J,
                    ActionEvent.CTRL_MASK));
            jMtmPaste.setMnemonic(java.awt.event.KeyEvent.VK_J);
            // END << jMtmVlozit
            // START >> jMtmOdstranit
            jMtmDelete = new JMenuItem();
            jMnuEdit.add(jMtmDelete);
            jMtmDelete.setText("Odstrániť");
            jMtmDelete.setActionCommand("Odstrániť");
            jMtmDelete.addActionListener(this);
            jMtmDelete.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menudelete.png")));
            jMtmDelete.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_DELETE, 0));
            jMtmDelete.setMnemonic(java.awt.event.KeyEvent.VK_O);
            // END << jMtmOdstranit
            // START >> jSprVymazat
            jSprDelete = new JSeparator();
            jMnuEdit.add(jSprDelete);
            // END << jSprVymazat
            // START >> jMtmFind
            jMtmFind = new JMenuItem();
            jMnuEdit.add(jMtmFind);
            jMtmFind.setText("H\u013eada\u0165");
            jMtmFind.setActionCommand("H\u013eada\u0165");
            jMtmFind.addActionListener(this);
            jMtmFind.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menusearch.png")));
            jMtmFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
                    ActionEvent.CTRL_MASK));
            jMtmFind.setMnemonic(java.awt.event.KeyEvent.VK_H);
            // END << jMtmFind
            // END << jMnuUpravy
            // START >> jMnuTest
            jMnuTest = new JMenu();
            jMbrMainMenu.add(jMnuTest);
            jMnuTest.setText("Test");
            jMnuTest.setMnemonic(java.awt.event.KeyEvent.VK_T);
            // START >> jMtmVytvorit
            jMtmNewTest = new JMenuItem();
            jMnuTest.add(jMtmNewTest);
            jMtmNewTest.setText("Nový");
            jMtmNewTest.setActionCommand("Nový");
            jMtmNewTest.addActionListener(this);
            jMtmNewTest.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menucreatetest.png")));
            jMtmNewTest.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
                    ActionEvent.CTRL_MASK));
            jMtmNewTest.setMnemonic(java.awt.event.KeyEvent.VK_N);
            // END << jMtmVytvorit
            // START >> jMnuVygenerovat
            jMtmGenerateTest = new JMenuItem();
            jMnuTest.add(jMtmGenerateTest);
            jMtmGenerateTest.setText("Generovať");
            jMtmGenerateTest.setActionCommand("Generovať");
            jMtmGenerateTest.addActionListener(this);
            jMtmGenerateTest.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menugentest.png")));
            jMtmGenerateTest.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_G, ActionEvent.CTRL_MASK));
            jMtmGenerateTest.setMnemonic(java.awt.event.KeyEvent.VK_G);
            // END << jMnuVygenerovat
            //START >> jSprAddQuestions
            jSprAddQuestions = new JSeparator();
            jMnuTest.add(jSprAddQuestions);
            // END << jSprAddQuestions
            // START >> jMtmAddQuestions
            jMtmAddQuestions = new JMenuItem();
            jMnuTest.add(jMtmAddQuestions);
            jMtmAddQuestions.setText("Pridať otázky do testu");
            jMtmAddQuestions.setActionCommand("Pridať do testu");
            jMtmAddQuestions.addActionListener(this);
            jMtmAddQuestions.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_R, ActionEvent.CTRL_MASK));
            jMtmAddQuestions.setMnemonic(java.awt.event.KeyEvent.VK_P);
            // END << jMtmAddQuestions
            // END << jMnuTest
            // START >> jMnuNapoveda
            jMnuHelp = new JMenu();
            jMbrMainMenu.add(jMnuHelp);
            jMnuHelp.setText("Nápoveda");
            jMnuHelp.setMnemonic(java.awt.event.KeyEvent.VK_N);
            // START >> jMtmPomoc
            jMtmHelp = new JMenuItem();
            jMnuHelp.add(jMtmHelp);
            jMtmHelp.setText("Pomoc");
            jMtmHelp.setActionCommand("Pomoc");
            jMtmHelp.addActionListener(this);
            jMtmHelp.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menuhelp.png")));
            jMtmHelp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
            jMtmHelp.setMnemonic(java.awt.event.KeyEvent.VK_P);
            // END << jMtmPomoc
            // START >> JSprOPrograme
            jSprAbout = new JSeparator();
            jMnuHelp.add(jSprAbout);
            // END << JSprOPrograme
            // START >> jMtmOPrograme
            jMtmAbout = new JMenuItem();
            jMnuHelp.add(jMtmAbout);
            jMtmAbout.setText("O programe ...");
            jMtmAbout.setActionCommand("O programe ...");
            jMtmAbout.addActionListener(this);
            jMtmAbout.setIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/menuabout.png")));
            jMtmAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,
                    ActionEvent.SHIFT_MASK));
            jMtmAbout.setMnemonic(java.awt.event.KeyEvent.VK_O);
            // END << jMtmOPrograme
            // END << jMnuNapoveda
            // END << jMbrMainMenu
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the jTreeTCategories
     */
    public JTree getJTreeTCategories() {
        return jTreeTCategories;
    }

    /**
     * @return the jTreeQCategories
     */
    public JTree getJTreeQCategories() {
        return jTreeQCategories;
    }

    @Override
    public void valueChanged(ListSelectionEvent evt) {
        int index = jTblQuestions.getSelectedRow();
        if (index == -1)
            return;
        Object item = genexTableModel.getValueAt(index, 1);
        if (item instanceof Question)
            jTxtQuestionText.setText(item.toString());
        else
            jTxtQuestionText.setText(((Category) item).getDescription());

        jTxtQuestionText.setCaretPosition(0);
    }

    public GenexTableModel getTableModel() {
        return genexTableModel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

        if ("Nová kategória".equals(command)) {
            if (jTabPane.getSelectedIndex() == 0)
                newCategory();
            else
                newTestCategory();
        } else if ("Nová otázka".equals(command)) {
            editQuestion(null);
        } else if ("Nastavenia".equals(command)) {
            PropertiesDialog pd = new PropertiesDialog(this);
            pd.setLocationRelativeTo(null);
            pd.setVisible(true);
        } else if ("Odstrániť".equals(command)) {
            if (lastSelTable)
                deleteSelectedItems();
            else
                deleteTests();
        } else if ("Upraviť".equals(command)) {
            int sel = jTblQuestions.getSelectedRow();
            if (sel == -1) {
                hint("Warning: Najprv si musíte vybrať kategóriu alebo otázku, ktorú chcete upraviť.");
                return;
            }
            Object obj = genexTableModel.getValue(sel);
            if (obj instanceof Category) {
                editCategory((Category) obj, sel);
            } else
                editQuestion((Question) obj);

        } else if ("Nový".equals(command)) {
            newTest();
        } else if ("Generovať".equals(command)) {
            generateTest();
        } else if ("Pridať do testu".equals(command)) {
            if (ntd.isVisible()) {
                addQuestionToTest();
            } else {
                newTest();
            }
        } else if ("Export testu".equals(command)) {
            exportTest();
        } else if ("Export testu do Moodle".equals(command)) {
            exportTestMoodle();
        } else if ("O úroven vyššie".equals(command)) {
            upDir();
        } else if ("Ukončiť".equals(command)) {
            this.setVisible(false);
            this.dispose();
            System.exit(0);
        } else if ("Kopírovať".equals(command)) {
            genexTableModel.copyData(jTblQuestions.getSelectedRows());
        } else if ("Vystrihnúť".equals(command)) {
            genexTableModel.cutData(jTblQuestions.getSelectedRows());
        } else if ("Vložiť".equals(command)) {
            pasteData();
        } else if ("Ísť na pôvodnú otázku".equals(command)) {
            jumpToDerivedFrom();
        } else {
            System.out.println("Unknown command: " + command);
        }
    }

    private void deleteTests() {
        TreePath tp = jTreeTCategories.getSelectionPath().getParentPath();
        DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) jTreeTCategories
                .getSelectionPath().getLastPathComponent();
        if (selNode == null) {
            hint("Warning: Vyberte si test alebo kategóriu testov na odstránenie.");
            return;
        }
        Object sel = selNode.getUserObject();
        Category c = null;
        Test t = null;
        String message = "Naozaj chcete odstrániť vybraný test?";

        try {
            if (sel instanceof Category) {
                c = (Category) sel;

                if (c.getName().equals("Všetky")) {
                    hint("Warning: Nie je možné vymazať korenovú kategóriu");
                    return;
                }

                message = "Naozaj chcete odstrániť vybranú testovú kategóriu?";

                int choice = JOptionPane.showConfirmDialog(this, message,
                        "Odstrániť testy", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if (choice == JOptionPane.NO_OPTION)
                    return;

                categoryDao.deleteTestCategory(c);

            } else {
                t = (Test) sel;

                int choice = JOptionPane.showConfirmDialog(this, message,
                        "Odstrániť testy", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if (choice == JOptionPane.NO_OPTION)
                    return;

                testDao.deleteTest(t);
            }
        } catch (TestInTestCategoryException e) {
            // TODO Auto-generated catch block
            deleteTestCategory(c);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        jTreeTCategories.collapsePath(tp);
        jTreeTCategories.expandPath(tp);
        jTreeTCategories.updateUI();
    }

    private void deleteTestCategory(Category c) {
        try {
            try {
                ArrayList<Test> tests = testDao.getTestsByCategoryID(c
                        .getCategoryID());
                for (Test t : tests) {
                    System.out.println(t.getName());
                    testDao.deleteTest(t);
                }

                ArrayList<Category> children = categoryDao
                        .getTestCategoriesByParentID(c.getCategoryID());
                for (Category cat : children) {
                    System.out.println(c.getName());
                    deleteTestCategory(cat);
                }

                categoryDao.deleteTestCategory(c);
            } catch (TestInTestCategoryException e) {
                //toto by uz nemalo nastat pretoze z kategorie sme uz udstranili aj testy aj podkategorie
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addQuestionToTest() {
        int[] sel = jTblQuestions.getSelectedRows();
        if (sel.length > 0) {
            for (int i = 0; i < sel.length; i++) {
                if (genexTableModel.getValue(sel[i]) instanceof Category)
                    continue;

                Question q = (Question) genexTableModel.getValue(sel[i]);
                ntd.getModel().addQuestion(q, new Float(q.getDifficulty()));
            }
        }
    }

    private Test assertTestChoosen() {
        if (jTabPane.getSelectedIndex() == 0) {
            hint("Info: Musíte vybrať test v ľavom paneli");
            return null;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTreeTCategories
                .getLastSelectedPathComponent();
        if (node == null) {
            hint("Info: Pred exportovaním vyberte test ktorý sa bude exportovať");
            return null;
        }
        Test test = null;
        if (node.getUserObject() instanceof Test) {
            test = (Test) node.getUserObject();
        } else {
            hint("Info: Exportovať je možné jedine testy");
            return null;
        }
        return test;
    }

    private void exportTestMoodle() {

        Test test = assertTestChoosen();
        if (test == null) {
            return;
        }

        JFileChooser jfc = new JFileChooser(".");
        jfc.setFileFilter(new FileNameExtensionFilter("XML súbory", "xml"));
        int state = jfc.showSaveDialog(this);
        if (state == JFileChooser.CANCEL_OPTION)
            return;

        File f = jfc.getSelectedFile();
        if (f == null)
            return;

        Export exp = new ExportMoodle();
        exp.setOutputFilename(f.getAbsolutePath());
        try {
            exp.exportQuestions(questionDao.getQuestionsByTestID(test
                    .getTestID()), connection);
            hint("Info: Export dokončený úspešne");
        } catch (Exception e) {
            hint("Error:" + e.getLocalizedMessage());
        }
        // TODO export do suboru f.getAbsoluteFile() abo tak dajak
    }

    private void exportTest() {
        Test test = assertTestChoosen();
        if (test == null) {
            return;
        }

        ExportTestDialog etd = new ExportTestDialog(this, test);
        etd.setLocationRelativeTo(null);
        etd.showDialog();
        if (etd.cancel)
            hint("Info: Export bol zrušený používaťeľom");
        else
            hint("Info: Export dokončený úspešne");
    }

    private void upDir() {
        TreePath path = (TreePath) jTblQuestions.getColumnModel().getColumn(1)
                .getHeaderValue();
        if (path == null || path.getParentPath() == null)
            return;
        jTreeQCategories.setSelectionPath(path.getParentPath());
    }

    private void newTestCategory() {
        TreePath path = jTreeTCategories.getSelectionPath();
        if (path == null)
            return;

        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        if (node == null)
            return;

        //zmena (snad to funguje :-) .. palo
        //Category cat = (Category) node.getUserObject();

        Object o = node.getUserObject();
        if (!(o instanceof Category))
            return;
        Category cat = (Category) o;

        NewCategoryDialog ncd = new NewCategoryDialog(this, null);
        ncd.setLocationRelativeTo(null);
        Category toAdd = ncd.showDialog();
        if (toAdd == null)
            return;

        try {
            toAdd.setUserTD(new UserDaoDerby(connection).getDefaultTUser()
                    .getUserID());

            categoryDao.addTestCategory(cat.getCategoryID(), toAdd);
            node.add(new DefaultMutableTreeNode("camuflage"));

            jTreeTCategories.collapsePath(path);
            jTreeTCategories.expandPath(path);
            jTreeTCategories.updateUI();
            hint("Info: Kategória pridaná úspešne");
        } catch (Exception e) {
            hint("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void setNewTestButton(boolean enabled) {
        jBtnNewTest.setEnabled(enabled);
    }

    private void newTest() {
        ArrayList<Question> list;
        int[] sel = jTblQuestions.getSelectedRows();
        if (sel.length > 0) {
            list = new ArrayList<Question>(sel.length);
            for (int i = 0; i < sel.length; i++) {
                if (genexTableModel.getValue(sel[i]) instanceof Category)
                    continue;
                list.add((Question) genexTableModel.getValue(sel[i]));
            }
        } else
            list = new ArrayList<Question>();
        NewTestTableModel testModel = new NewTestTableModel(connection);
        try {
            testModel.setQuestions(list, null);
        } catch (Exception e) {
            hint("Error: " + e.getLocalizedMessage());
            e.printStackTrace();
        }
        TreePath path = jTreeTCategories.getSelectionPath();
        if (path == null) {
            hint("Warning: Musíte si vybrať kategóriu testu.");
            return;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        Object obj = node.getUserObject();
        if (obj instanceof Test) {
            hint("Warning: Musíte si vybrať kategóriu testu.");
            return;
        }
        Category testCat = (Category) obj;
        ntd = new NewTestDialog(this, testModel, genexTableModel, testCat, null);
        ntd.setLocationRelativeTo(null);
        ntd.setVisible(true);
    }

    public void updateTestTree() {
        TreePath path = jTreeTCategories.getSelectionPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        node.add(new DefaultMutableTreeNode("camuflage"));
        jTreeTCategories.collapsePath(path);
        jTreeTCategories.expandPath(path);
        jTreeTCategories.updateUI();
        hint("Info: Nový test vytvorený úspešne");
    }

    private void generateTest() {

        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTreeTCategories
                .getLastSelectedPathComponent();
        if (node == null) {
            hint("Warning: Musíte si vybrať kategóriu testu.");
            return;
        }
        Object obj = node.getUserObject();
        if (obj instanceof Test) {
            hint("Warning: Musíte si vybrať kategóriu testu.");
            return;
        }
        Category testCat = (Category) obj;
        GenerateTestDialog gtd = new GenerateTestDialog(this, connection);
        gtd.setLocationRelativeTo(null);
        try {
            if (gtd.showDialog() == JOptionPane.OK_OPTION) {

                NewTestTableModel nttm = new NewTestTableModel(connection, gtd
                        .getGeneratedTest());

                NewTestDialog ntd = new NewTestDialog(this, nttm,
                        this.genexTableModel, testCat, null);
                ntd.setLocationRelativeTo(null);
                ntd.setTitle("Vygenerovaný test");
                ntd.setVisible(true);
            }
        } catch (SQLException e) {
            hint("Error: " + e.getMessage());
        }

        node.add(new DefaultMutableTreeNode("camuflage"));
        TreePath path = new TreePath(node.getPath());
        if (path.getParentPath() == null) {
            jTreeTCategories.collapsePath(path);
            jTreeTCategories.expandPath(path);
        } else {
            jTreeTCategories.collapsePath(path.getParentPath());
            jTreeTCategories.expandPath(path.getParentPath());
        }
        jTreeTCategories.updateUI();
        hint("Info: Bol vygenerovaný nový test v kategórii " + testCat);
    }

    private void deleteSelectedItems() {
        // TODO zmazu sa vybrane polozky z tabulky
        int[] selIndices = jTblQuestions.getSelectedRows();
        if (selIndices.length == 0) {
            hint("Warning: Najprv vyberte z tabuľky položky, ktoré chcete odstrániť.");
            return;
        }

        int choice = JOptionPane.showConfirmDialog(this,
                "Naozaj chcete odstrániť vybrané položky?",
                "Odstrániť kategórie/otázky", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (choice == JOptionPane.NO_OPTION)
            return;

        genexTableModel.deleteItems(selIndices);
        TreePath tp = (TreePath) jTblQuestions.getColumnModel().getColumn(1)
                .getHeaderValue();

        jTreeQCategories.collapsePath(tp);
        jTreeQCategories.expandPath(tp);

        jTreeQCategories.updateUI();
    }

    public void editCategory(Category toEdit, int selected) {
        if (toEdit.getName().equals("Kôš")
                || toEdit.getName().equals("Konflikty")) {
            hint("Info: Túto kategóriu nemôžete upravovať ani zmazať.");
            return;
        }
        NewCategoryDialog ncd = new NewCategoryDialog(this, toEdit);
        ncd.setLocationRelativeTo(null);
        Category c = ncd.showDialog();
        if (c == null)
            return;
        //TODO
        //pridane odchytavanie vynimiek (palo)
        try {
            categoryDao.updateCategory(c);
        } catch (Exception e) {
            hint("Error: " + e.getMessage());
        }
        genexTableModel.fireTableDataChanged();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTreeQCategories
                .getLastSelectedPathComponent();
        if (node == null)
            return;
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) node
                .getChildAt(selected);
        child.setUserObject(c);
        jTreeQCategories.updateUI();
    }

    /**
     * Zobrazi dialog na vytvorenie novej otazky
     */
    private void editQuestion(Question question) {
        TreePath path = jTreeQCategories.getSelectionPath();
        if (path == null) {
            hint("Warning: Najprv si musíte vybrať ketgóriu, v ktorej chcete otázku vytvoriť.");
            return;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        Category parent = (Category) node.getUserObject();
        ArrayList<Category> arr_categories = new ArrayList<Category>();
        arr_categories.add(parent);
        NewQuestionDialog nqd = new NewQuestionDialog(this, arr_categories,
                question, connection);
        nqd.setLocationRelativeTo(null);
        Question q = nqd.showDialog();
        if (q == null)
            return;

        genexTableModel.fireTableDataChanged();
    }

    /**
     * Zobrazi dialog na vytvorenie novej kategorie
     */
    private void newCategory() {
        NewCategoryDialog d = new NewCategoryDialog(this, null);
        d.setLocationRelativeTo(null);
        Category toAdd = d.showDialog();
        if (toAdd == null)
            return;
        //TODO
        //pridane odchytavanie vynimiek (palo)
        try {
            toAdd.setUserTD(userDao.getDefaultTUser().getUserID());
        } catch (Exception e) {
            hint("Error: " + e.getMessage());
        }
        DefaultMutableTreeNode node;
        TreePath path = jTreeQCategories.getSelectionPath();
        node = null; //pozor mozna chyba
        //TODO
        //pridane odchytavanie vynimiek (palo)
        try {
            if (path == null) {
                node = rootQuestionCategoryNode;
                categoryDao.addRootCategory(toAdd);
            } else {
                node = (DefaultMutableTreeNode) path.getLastPathComponent();
                Category parent = (Category) node.getUserObject();
                categoryDao.addCategory(parent.getCategoryID(), toAdd);
            }
        } catch (Exception e) {
            hint("Error: " + e.getMessage());
        }
        node.add(new DefaultMutableTreeNode(toAdd));
        jTreeQCategories.updateUI();
        genexTableModel.fireTableDataChanged();
    }

    private void hint(String text) {
        if (jTxtHint.getBackground() == COMB1_BACKGROUND_COLOR) {
            jTxtHint.setBackground(COMB2_BACKGROUND_COLOR);
            jTxtHint.setForeground(COMB2_FOREGROUND_COLOR);
        } else {
            jTxtHint.setBackground(COMB1_BACKGROUND_COLOR);
            jTxtHint.setForeground(COMB1_FOREGROUND_COLOR);
        }
        if (text.startsWith("Error:")) {
            jTxtHint.setText(text.substring(6));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/error.png")));
        } else if (text.startsWith("Warning:")) {
            jTxtHint.setText(text.substring(8));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/warning.png")));
        } else if (text.startsWith("Info:")) {
            jTxtHint.setText(text.substring(5));
            jTxtHint.setCaretPosition(0);
            jTxtHint.insertIcon(new ImageIcon(resHelp
                    .getResourceBytes("/icons/info.png")));
        } else {
            jTxtHint.setText(text);
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() != 2)
            return;

        int index = jTblQuestions.getSelectedRow();
        if (index == -1)
            return;
        Object item = genexTableModel.getValueAt(index, 1);

        if (item instanceof Category) {
            changeCategory(index);
        } else if (item instanceof Question) {
            editQuestion((Question) item);
        } else {
            hint("Warning: Neznámy objekt " + item.getClass());
        }
    }

    public void changeCategory(int index) {
        TreePath lastSel = (TreePath) jTblQuestions.getColumnModel().getColumn(
                1).getHeaderValue();
        if (lastSel == null)
            return;
        jTreeQCategories.expandPath(lastSel);

        DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) lastSel
                .getLastPathComponent();
        if (dmtn == null)
            return;
        TreeNode tn = dmtn.getChildAt(index);

        TreePath tp = lastSel.pathByAddingChild(tn);
        jTreeQCategories.setSelectionPath(tp);
    }

    public void pasteData() {
        try {
            genexTableModel.pasteData();
            genexTableModel.fireTableDataChanged();
            TreePath tp = (TreePath) jTblQuestions.getColumnModel()
                    .getColumn(1).getHeaderValue();

            if (tp.getParentPath() == null) {
                jTreeQCategories.collapsePath(tp);
                jTreeQCategories.expandPath(tp);
            } else {
                jTreeQCategories.collapsePath(tp.getParentPath());
                jTreeQCategories.expandPath(tp.getParentPath());
            }
            jTreeQCategories.updateUI();
        } catch (SQLException sex) {
            hint("Error: " + sex.getLocalizedMessage());
        }
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    /**
     * Auto-generated method for setting the popup menu for a component
     */
    private void setComponentPopupMenu(final java.awt.Component parent,
            final javax.swing.JPopupMenu menu) {
        parent.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger())
                    menu.show(parent, e.getX(), e.getY());
            }

            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger())
                    menu.show(parent, e.getX(), e.getY());
            }
        });
    }

    @Override
    public void valueChanged(TreeSelectionEvent e) {
        TreePath path = e.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();

        if (node.getUserObject() instanceof Test) {
            jBtnNewQCategory.setEnabled(false);
        } else {
            jBtnNewQCategory.setEnabled(true);
        }

    }

    @Override
    public void stateChanged(ChangeEvent e) {
        if (jBtnNewQCategory == null)
            return;
        if (jTabPane.getSelectedIndex() == 0) {
            jBtnNewQCategory.setEnabled(true);
        } else {
            TreePath path = jTreeTCategories.getSelectionPath();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                    .getLastPathComponent();

            if (node.getUserObject() instanceof Test) {
                jBtnNewQCategory.setEnabled(false);
            } else {
                jBtnNewQCategory.setEnabled(true);
            }
        }
    }

    private void jTreeTCategoriesMouseClicked(MouseEvent evt) {
        if (evt.getClickCount() != 2)
            return;
        TreePath path = jTreeTCategories.getSelectionPath();
        if (path == null)
            return;
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        Object obj = node.getUserObject();
        if (obj instanceof Category)
            return;
        Test test = (Test) obj;
        Category category = (Category) (((DefaultMutableTreeNode) node
                .getParent()).getUserObject());
        try {
            ntd = new NewTestDialog(this, new NewTestTableModel(connection,
                    test), genexTableModel, category, test);
            ntd.setLocationRelativeTo(null);
            ntd.setVisible(true);
            jTreeTCategories.updateUI();
        } catch (SQLException e) {
            hint("Error:" + e.getMessage());
        }
    }

    private void jumpToDerivedFrom() {
        // fck this shit, not needed now
    }
}
